package main

import (
	"encoding/json"
	"log"
	"runtime"

	"gitee.com/shiwjlinux/MessageQueue/nats01/model"
	"github.com/nats-io/nats.go"
)

func main() {
	// Connect to NATS
	nc, _ := nats.Connect(model.NatsURL)
	js, err := nc.JetStream()
	if err != nil {
		log.Fatal(err)
	}

	// Create durable consumer monitor
	js.Subscribe(model.StreamSubjects, func(msg *nats.Msg) {
		msg.Ack()
		var order model.Order
		err := json.Unmarshal(msg.Data, &order)
		if err != nil {
			log.Fatal(err)
		}

		log.Printf("monitor service subscribes from subject:%s\n",
			msg.Subject)

		log.Printf("OrderID:%d, CustormerID:%s, Status:%s\n",
			order.OrderID, order.CustormerID, order.Status)
	}, nats.Durable("monitor"), nats.ManualAck())

	// 只要有协程在运行，程序就不会退出
	// 只退出main函数，不会退出整个程序
	runtime.Goexit()
}
